import React, { useEffect, useState } from 'react';
import {
  Row,
  Col,
  Button,
  Empty,
  Spin,
  Input,
  Select,
  Space,
  Modal,
  message,
} from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  AppstoreOutlined,
  UnorderedListOutlined,
  HolderOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
  DragStartEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  rectSortingStrategy,
  useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { useProjectStore } from '@/stores/project.store';
import { ProjectCard } from '@/components/project/ProjectCard';
import { CreateProjectModal } from '@/components/project/CreateProjectModal';
import { useBreakpoint } from '@/hooks/useBreakpoint';
import BottomNavigation from '@/components/navigation/BottomNavigation';
import type { Project, CreateProjectDto } from '@/types/project';
import './style.css';

const { Search } = Input;
const { Option } = Select;

// 可拖拽的项目卡片包装器
interface SortableProjectCardProps {
  project: Project;
  onClick: (project: Project) => void;
  onEdit: (project: Project) => void;
  onDelete: (project: Project) => void;
  onDuplicate: (project: Project) => void;
}

const SortableProjectCard: React.FC<SortableProjectCardProps> = ({
  project,
  onClick,
  onEdit,
  onDelete,
  onDuplicate,
}) => {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
    useSortable({ id: project.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div ref={setNodeRef} style={style} {...attributes}>
      <div className="sortable-project-wrapper">
        <div className="drag-handle" {...listeners}>
          <HolderOutlined />
        </div>
        <ProjectCard
          project={project}
          onClick={onClick}
          onEdit={onEdit}
          onDelete={onDelete}
          onDuplicate={onDuplicate}
          isDragging={isDragging}
        />
      </div>
    </div>
  );
};

const ProjectsPage: React.FC = () => {
  const navigate = useNavigate();
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  const {
    projects,
    isLoading,
    fetchProjects,
    createProject,
    updateProject,
    deleteProject,
    duplicateProject,
    reorderProjects,
  } = useProjectStore();

  // 检查URL参数，如果有?create=true则自动打开创建模态框
  const searchParams = new URLSearchParams(window.location.search);
  const shouldOpenCreate = searchParams.get('create') === 'true';

  const [createModalOpen, setCreateModalOpen] = useState(shouldOpenCreate);
  const [editingProject, setEditingProject] = useState<Project | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<'updatedAt' | 'createdAt' | 'name'>('updatedAt');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [draggingId, setDraggingId] = useState<string | null>(null);

  // 拖拽传感器配置
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8, // 移动8px后才开始拖拽,避免误触
      },
    }),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  useEffect(() => {
    fetchProjects({ sortBy, sortOrder: 'desc' });
  }, [fetchProjects, sortBy]);

  // 清理URL参数
  useEffect(() => {
    if (shouldOpenCreate && window.history.replaceState) {
      window.history.replaceState({}, '', window.location.pathname);
    }
  }, [shouldOpenCreate]);

  // 处理创建项目
  const handleCreateProject = async (data: CreateProjectDto) => {
    const project = await createProject(data);
    if (project) {
      setCreateModalOpen(false);
    }
  };

  // 处理编辑项目
  const handleEditProject = (project: Project) => {
    setEditingProject(project);
    setCreateModalOpen(true);
  };

  // 处理删除项目
  const handleDeleteProject = (project: Project) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除项目"${project.name}"吗？此操作不可撤销。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        await deleteProject(project.id);
      },
    });
  };

  // 处理复制项目
  const handleDuplicateProject = (project: Project) => {
    Modal.confirm({
      title: '复制项目',
      content: `确定要复制项目"${project.name}"吗?`,
      okText: '复制',
      cancelText: '取消',
      onOk: async () => {
        await duplicateProject(project.id, `${project.name} (副本)`);
      },
    });
  };

  // 处理点击项目卡片
  const handleProjectClick = (project: Project) => {
    // 跳转到编辑器页面或项目详情页
    navigate(`/projects/${project.id}/editor`);
  };

  // 处理拖拽开始
  const handleDragStart = (event: DragStartEvent) => {
    setDraggingId(event.active.id as string);
  };

  // 处理拖拽结束
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    setDraggingId(null);

    if (over && active.id !== over.id) {
      const oldIndex = projects.findIndex((p) => p.id === active.id);
      const newIndex = projects.findIndex((p) => p.id === over.id);

      const newProjects = arrayMove(projects, oldIndex, newIndex);
      const projectIds = newProjects.map((p) => p.id);

      // 乐观更新已在store中处理
      reorderProjects(projectIds);
    }
  };

  // 过滤和排序项目
  const filteredProjects = projects.filter((project) =>
    searchQuery
      ? project.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        project.description?.toLowerCase().includes(searchQuery.toLowerCase())
      : true
  );

  return (
    <div className={`projects-page ${isMobile ? 'mobile' : 'desktop'}`}>
      {/* 顶部操作栏 */}
      <div className="projects-header">
        <div className="projects-title">
          <h1>项目管理</h1>
          <span className="projects-count">{projects.length} 个项目</span>
        </div>

        <div className="projects-actions">
          <Space size="middle" wrap>
            {/* 搜索框 */}
            <Search
              placeholder="搜索项目..."
              allowClear
              style={{ width: isMobile ? '100%' : 240 }}
              prefix={<SearchOutlined />}
              onChange={(e) => setSearchQuery(e.target.value)}
            />

            {/* 排序选择器 */}
            {!isMobile && (
              <Select
                value={sortBy}
                onChange={setSortBy}
                style={{ width: 140 }}
              >
                <Option value="updatedAt">最近更新</Option>
                <Option value="createdAt">创建时间</Option>
                <Option value="name">名称</Option>
              </Select>
            )}

            {/* 视图切换 */}
            {!isMobile && (
              <Space.Compact>
                <Button
                  type={viewMode === 'grid' ? 'primary' : 'default'}
                  icon={<AppstoreOutlined />}
                  onClick={() => setViewMode('grid')}
                />
                <Button
                  type={viewMode === 'list' ? 'primary' : 'default'}
                  icon={<UnorderedListOutlined />}
                  onClick={() => setViewMode('list')}
                />
              </Space.Compact>
            )}

            {/* 新建项目按钮 */}
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingProject(null);
                setCreateModalOpen(true);
              }}
              size={isMobile ? 'middle' : 'large'}
            >
              {isMobile ? '新建' : '新建项目'}
            </Button>
          </Space>
        </div>
      </div>

      {/* 项目列表 */}
      <div className="projects-content">
        {isLoading ? (
          <div className="projects-loading">
            <Spin size="large" tip="加载中..." />
          </div>
        ) : filteredProjects.length === 0 ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={searchQuery ? '未找到匹配的项目' : '暂无项目'}
            className="projects-empty"
          >
            {!searchQuery && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setCreateModalOpen(true)}
              >
                创建第一个项目
              </Button>
            )}
          </Empty>
        ) : (
          <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragStart={handleDragStart}
            onDragEnd={handleDragEnd}
          >
            <SortableContext
              items={filteredProjects.map((p) => p.id)}
              strategy={rectSortingStrategy}
            >
              <Row gutter={[16, 16]} className={`projects-grid ${viewMode}`}>
                {filteredProjects.map((project) => (
                  <Col
                    xs={24}
                    sm={12}
                    md={viewMode === 'grid' ? 8 : 24}
                    lg={viewMode === 'grid' ? 6 : 24}
                    xl={viewMode === 'grid' ? 6 : 24}
                    key={project.id}
                  >
                    <SortableProjectCard
                      project={project}
                      onClick={handleProjectClick}
                      onEdit={handleEditProject}
                      onDelete={handleDeleteProject}
                      onDuplicate={handleDuplicateProject}
                    />
                  </Col>
                ))}
              </Row>
            </SortableContext>
          </DndContext>
        )}
      </div>

      {/* 新建/编辑项目模态框 */}
      <CreateProjectModal
        open={createModalOpen}
        onCancel={() => {
          setCreateModalOpen(false);
          setEditingProject(null);
        }}
        onOk={handleCreateProject}
        loading={isLoading}
      />

      {/* 移动端底部导航 */}
      {isMobile && <BottomNavigation activeKey="projects" />}
    </div>
  );
};

export default ProjectsPage;
